"""
界面自适应器服务实现

提供智能界面自适应功能，包括：
- 界面布局优化算法
- 个性化界面配置
- 界面适应性逻辑
- 用户体验优化
"""
import json
import math
from typing import List, Dict, Any, Optional, Tuple, Set
from datetime import datetime, timedelta
from dataclasses import dataclass, asdict, replace, field
from collections import defaultdict, Counter
from enum import Enum

from ..models.analysis_models import (
    UserBehavior, UserPreferences, Context, InterfaceConfig
)
from .preference_analysis_service import PreferenceAnalysisService
from .user_behavior_service import UserBehaviorService


class LayoutType(Enum):
    """布局类型枚举"""
    COMPACT = "compact"
    STANDARD = "standard"
    SPACIOUS = "spacious"
    CUSTOM = "custom"


class ComponentType(Enum):
    """组件类型枚举"""
    NAVIGATION = "navigation"
    TOOLBAR = "toolbar"
    SIDEBAR = "sidebar"
    MAIN_CONTENT = "main_content"
    STATUS_BAR = "status_bar"
    PANEL = "panel"
    WIDGET = "widget"


class AdaptationTrigger(Enum):
    """适应触发器枚举"""
    USER_BEHAVIOR = "user_behavior"
    PREFERENCE_CHANGE = "preference_change"
    CONTEXT_CHANGE = "context_change"
    PERFORMANCE_ISSUE = "performance_issue"
    USER_FEEDBACK = "user_feedback"


@dataclass
class InterfaceComponent:
    """界面组件"""
    component_id: str = ""
    component_type: ComponentType = ComponentType.WIDGET
    title: str = ""
    description: str = ""
    position: Dict[str, Any] = field(default_factory=dict)  # x, y, width, height
    visibility: bool = True
    priority: int = 5  # 1-10, 10为最高优先级
    usage_frequency: float = 0.0
    last_used: Optional[datetime] = None
    customizable: bool = True
    dependencies: List[str] = field(default_factory=list)
    
    def __post_init__(self):
        if not self.position:
            self.position = {"x": 0, "y": 0, "width": 100, "height": 50}


@dataclass
class LayoutConfiguration:
    """布局配置"""
    layout_id: str = ""
    layout_type: LayoutType = LayoutType.STANDARD
    name: str = ""
    description: str = ""
    components: List[InterfaceComponent] = field(default_factory=list)
    grid_size: Tuple[int, int] = (12, 8)  # 网格大小
    responsive_breakpoints: Dict[str, int] = field(default_factory=dict)
    theme_settings: Dict[str, Any] = field(default_factory=dict)
    created_at: datetime = field(default_factory=datetime.now)
    
    def __post_init__(self):
        if not self.responsive_breakpoints:
            self.responsive_breakpoints = {
                "mobile": 768,
                "tablet": 1024,
                "desktop": 1440
            }
        if not self.theme_settings:
            self.theme_settings = {
                "color_scheme": "default",
                "font_size": 14,
                "density": "medium"
            }


@dataclass
class AdaptationRule:
    """适应规则"""
    rule_id: str = ""
    name: str = ""
    trigger: AdaptationTrigger = AdaptationTrigger.USER_BEHAVIOR
    conditions: List[Dict[str, Any]] = field(default_factory=list)
    actions: List[Dict[str, Any]] = field(default_factory=list)
    priority: int = 5
    enabled: bool = True
    success_rate: float = 0.0
    usage_count: int = 0


@dataclass
class UserExperienceMetrics:
    """用户体验指标"""
    user_id: str = ""
    session_id: str = ""
    task_completion_time: float = 0.0
    click_efficiency: float = 0.0  # 有效点击 / 总点击
    navigation_depth: int = 0
    error_rate: float = 0.0
    satisfaction_score: float = 0.0
    interface_usage_pattern: Dict[str, float] = field(default_factory=dict)
    timestamp: datetime = field(default_factory=datetime.now)


class InterfaceAdapterService:
    """界面自适应器服务"""
    
    def __init__(self, 
                 preference_service: Optional[PreferenceAnalysisService] = None,
                 behavior_service: Optional[UserBehaviorService] = None):
        self.preference_service = preference_service or PreferenceAnalysisService()
        self.behavior_service = behavior_service or UserBehaviorService()
        
        # 界面配置存储
        self.user_interface_configs: Dict[str, InterfaceConfig] = {}
        self.layout_configurations: Dict[str, LayoutConfiguration] = {}
        self.interface_components: Dict[str, InterfaceComponent] = {}
        
        # 适应规则和历史
        self.adaptation_rules: List[AdaptationRule] = []
        self.adaptation_history: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
        
        # 用户体验数据
        self.ux_metrics: Dict[str, List[UserExperienceMetrics]] = defaultdict(list)
        self.component_usage_stats: Dict[str, Dict[str, float]] = defaultdict(dict)
        
        # 适应配置
        self.adaptation_config = {
            'min_usage_threshold': 0.1,  # 最小使用阈值
            'adaptation_sensitivity': 0.3,  # 适应敏感度
            'layout_optimization_interval': 7,  # 布局优化间隔（天）
            'component_visibility_threshold': 0.05,  # 组件可见性阈值
            'performance_threshold': 2.0,  # 性能阈值（秒）
            'max_components_per_view': 15  # 每个视图最大组件数
        }
        
        # 初始化默认组件和布局
        self._initialize_default_components()
        self._initialize_default_layouts()
        self._initialize_adaptation_rules()
    
    def _initialize_default_components(self):
        """初始化默认界面组件"""
        default_components = [
            # 导航组件
            ("main_navigation", ComponentType.NAVIGATION, "主导航", "系统主要导航菜单", 
             {"x": 0, "y": 0, "width": 12, "height": 1}, 10),
            ("breadcrumb", ComponentType.NAVIGATION, "面包屑导航", "当前位置导航", 
             {"x": 0, "y": 1, "width": 12, "height": 1}, 7),
            
            # 工具栏组件
            ("main_toolbar", ComponentType.TOOLBAR, "主工具栏", "常用功能工具栏", 
             {"x": 0, "y": 2, "width": 12, "height": 1}, 9),
            ("quick_actions", ComponentType.TOOLBAR, "快速操作", "快速操作按钮组", 
             {"x": 9, "y": 2, "width": 3, "height": 1}, 8),
            
            # 侧边栏组件
            ("left_sidebar", ComponentType.SIDEBAR, "左侧边栏", "功能面板和导航", 
             {"x": 0, "y": 3, "width": 2, "height": 4}, 6),
            ("right_sidebar", ComponentType.SIDEBAR, "右侧边栏", "属性面板和工具", 
             {"x": 10, "y": 3, "width": 2, "height": 4}, 5),
            
            # 主内容区域
            ("main_content", ComponentType.MAIN_CONTENT, "主内容区", "主要工作区域", 
             {"x": 2, "y": 3, "width": 8, "height": 4}, 10),
            
            # 面板组件
            ("properties_panel", ComponentType.PANEL, "属性面板", "对象属性编辑", 
             {"x": 10, "y": 3, "width": 2, "height": 2}, 6),
            ("history_panel", ComponentType.PANEL, "历史面板", "操作历史记录", 
             {"x": 10, "y": 5, "width": 2, "height": 2}, 4),
            ("help_panel", ComponentType.PANEL, "帮助面板", "上下文帮助信息", 
             {"x": 0, "y": 5, "width": 2, "height": 2}, 3),
            
            # 小部件
            ("search_widget", ComponentType.WIDGET, "搜索框", "全局搜索功能", 
             {"x": 6, "y": 0, "width": 3, "height": 1}, 8),
            ("notification_widget", ComponentType.WIDGET, "通知中心", "系统通知显示", 
             {"x": 9, "y": 0, "width": 2, "height": 1}, 7),
            ("progress_widget", ComponentType.WIDGET, "进度指示器", "任务进度显示", 
             {"x": 11, "y": 0, "width": 1, "height": 1}, 6),
            
            # 状态栏
            ("status_bar", ComponentType.STATUS_BAR, "状态栏", "系统状态信息", 
             {"x": 0, "y": 7, "width": 12, "height": 1}, 8),
        ]
        
        for comp_id, comp_type, title, desc, position, priority in default_components:
            component = InterfaceComponent(
                component_id=comp_id,
                component_type=comp_type,
                title=title,
                description=desc,
                position=position,
                priority=priority,
                customizable=True
            )
            self.interface_components[comp_id] = component
    
    def _initialize_default_layouts(self):
        """初始化默认布局配置"""
        # 紧凑布局
        compact_components = [
            self.interface_components["main_navigation"],
            self.interface_components["main_toolbar"],
            self.interface_components["main_content"],
            self.interface_components["quick_actions"],
            self.interface_components["search_widget"],
            self.interface_components["status_bar"]
        ]
        
        compact_layout = LayoutConfiguration(
            layout_id="compact",
            layout_type=LayoutType.COMPACT,
            name="紧凑布局",
            description="适合小屏幕和高效工作的紧凑界面",
            components=compact_components,
            theme_settings={
                "color_scheme": "dark",
                "font_size": 12,
                "density": "high"
            }
        )
        self.layout_configurations["compact"] = compact_layout
        
        # 标准布局
        standard_components = list(self.interface_components.values())[:10]
        
        standard_layout = LayoutConfiguration(
            layout_id="standard",
            layout_type=LayoutType.STANDARD,
            name="标准布局",
            description="平衡功能和美观的标准界面",
            components=standard_components,
            theme_settings={
                "color_scheme": "default",
                "font_size": 14,
                "density": "medium"
            }
        )
        self.layout_configurations["standard"] = standard_layout
        
        # 宽松布局
        spacious_components = list(self.interface_components.values())
        
        spacious_layout = LayoutConfiguration(
            layout_id="spacious",
            layout_type=LayoutType.SPACIOUS,
            name="宽松布局",
            description="适合大屏幕和详细工作的宽松界面",
            components=spacious_components,
            theme_settings={
                "color_scheme": "light",
                "font_size": 16,
                "density": "low"
            }
        )
        self.layout_configurations["spacious"] = spacious_layout
    
    def _initialize_adaptation_rules(self):
        """初始化适应规则"""
        rules = [
            # 基于使用频率的组件可见性规则
            AdaptationRule(
                rule_id="hide_unused_components",
                name="隐藏未使用组件",
                trigger=AdaptationTrigger.USER_BEHAVIOR,
                conditions=[
                    {"type": "component_usage", "operator": "<", "value": 0.05, "period_days": 7}
                ],
                actions=[
                    {"type": "set_visibility", "target": "component", "value": False}
                ],
                priority=6
            ),
            
            # 基于专业水平的界面复杂度规则
            AdaptationRule(
                rule_id="adjust_complexity_by_expertise",
                name="根据专业水平调整复杂度",
                trigger=AdaptationTrigger.PREFERENCE_CHANGE,
                conditions=[
                    {"type": "expertise_level", "operator": "==", "value": "beginner"}
                ],
                actions=[
                    {"type": "switch_layout", "target": "layout", "value": "compact"},
                    {"type": "hide_advanced_components", "target": "components"}
                ],
                priority=8
            ),
            
            # 基于屏幕尺寸的响应式规则
            AdaptationRule(
                rule_id="responsive_layout",
                name="响应式布局调整",
                trigger=AdaptationTrigger.CONTEXT_CHANGE,
                conditions=[
                    {"type": "screen_width", "operator": "<", "value": 768}
                ],
                actions=[
                    {"type": "switch_layout", "target": "layout", "value": "compact"},
                    {"type": "collapse_sidebars", "target": "sidebars"}
                ],
                priority=9
            ),
            
            # 基于任务类型的界面优化规则
            AdaptationRule(
                rule_id="task_specific_optimization",
                name="任务特定界面优化",
                trigger=AdaptationTrigger.CONTEXT_CHANGE,
                conditions=[
                    {"type": "current_task", "operator": "in", "value": ["data_analysis", "visualization"]}
                ],
                actions=[
                    {"type": "show_component", "target": "component", "value": "properties_panel"},
                    {"type": "expand_main_content", "target": "main_content"}
                ],
                priority=7
            ),
            
            # 基于性能的优化规则
            AdaptationRule(
                rule_id="performance_optimization",
                name="性能优化",
                trigger=AdaptationTrigger.PERFORMANCE_ISSUE,
                conditions=[
                    {"type": "response_time", "operator": ">", "value": 2.0}
                ],
                actions=[
                    {"type": "reduce_animations", "target": "interface"},
                    {"type": "lazy_load_components", "target": "components"}
                ],
                priority=10
            )
        ]
        
        self.adaptation_rules = rules
    
    async def adapt_interface(self, user_id: str, context: Optional[Context] = None) -> InterfaceConfig:
        """自适应界面配置"""
        try:
            # 获取用户偏好
            if user_id not in self.preference_service.user_preferences:
                await self.preference_service.update_preference_model(user_id)
            
            user_preferences = self.preference_service.user_preferences.get(user_id)
            
            # 获取当前界面配置
            current_config = self.user_interface_configs.get(user_id, InterfaceConfig())
            
            # 分析用户行为模式
            behavior_analysis = await self._analyze_interface_behavior(user_id)
            
            # 应用适应规则
            adapted_config = await self._apply_adaptation_rules(
                user_id, current_config, user_preferences, context, behavior_analysis
            )
            
            # 优化布局
            optimized_config = await self._optimize_layout(
                user_id, adapted_config, user_preferences, behavior_analysis
            )
            
            # 更新用户配置
            self.user_interface_configs[user_id] = optimized_config
            
            # 记录适应历史
            self._record_adaptation(user_id, current_config, optimized_config)
            
            return optimized_config
            
        except Exception as e:
            print(f"界面自适应失败: {e}")
            return self.user_interface_configs.get(user_id, InterfaceConfig())
    
    async def _analyze_interface_behavior(self, user_id: str) -> Dict[str, Any]:
        """分析界面使用行为"""
        analysis = {
            'component_usage': {},
            'navigation_patterns': [],
            'interaction_efficiency': 0.0,
            'preferred_layout_density': 'medium',
            'peak_usage_times': [],
            'error_prone_areas': []
        }
        
        try:
            # 获取用户行为数据
            protected_user_id = await self.behavior_service._protect_user_id(user_id)
            
            if protected_user_id not in self.behavior_service.behavior_data:
                return analysis
            
            behaviors = self.behavior_service.behavior_data[protected_user_id]
            recent_behaviors = [b for b in behaviors 
                             if (datetime.now() - b.created_at).days <= 30]
            
            if not recent_behaviors:
                return analysis
            
            # 分析组件使用频率
            ui_behaviors = [b for b in recent_behaviors 
                          if any(ui_term in b.action_type.lower() 
                               for ui_term in ['click', 'view', 'navigate', 'menu', 'panel'])]
            
            component_counts = Counter()
            for behavior in ui_behaviors:
                # 从行为上下文中提取组件信息
                if 'component' in behavior.context:
                    component_counts[behavior.context['component']] += 1
                elif 'view' in behavior.context:
                    component_counts[behavior.context['view']] += 1
            
            total_ui_actions = len(ui_behaviors)
            if total_ui_actions > 0:
                analysis['component_usage'] = {
                    comp: count / total_ui_actions 
                    for comp, count in component_counts.items()
                }
            
            # 分析交互效率
            successful_actions = sum(1 for b in ui_behaviors if b.success)
            analysis['interaction_efficiency'] = (
                successful_actions / total_ui_actions if total_ui_actions > 0 else 0.0
            )
            
            # 分析布局密度偏好
            avg_session_actions = len(recent_behaviors) / max(1, len(set(b.created_at.date() for b in recent_behaviors)))
            if avg_session_actions > 25:
                analysis['preferred_layout_density'] = 'high'
            elif avg_session_actions < 15:
                analysis['preferred_layout_density'] = 'low'
            
            # 分析使用时间模式
            hour_counts = Counter(b.created_at.hour for b in recent_behaviors)
            analysis['peak_usage_times'] = [hour for hour, count in hour_counts.most_common(3)]
            
            # 分析错误易发区域
            failed_behaviors = [b for b in ui_behaviors if not b.success]
            error_areas = Counter()
            for behavior in failed_behaviors:
                if 'component' in behavior.context:
                    error_areas[behavior.context['component']] += 1
            
            analysis['error_prone_areas'] = [area for area, count in error_areas.most_common(3)]
            
        except Exception as e:
            print(f"界面行为分析失败: {e}")
        
        return analysis
    
    async def _apply_adaptation_rules(self, 
                                   user_id: str,
                                   current_config: InterfaceConfig,
                                   user_preferences: Optional[UserPreferences],
                                   context: Optional[Context],
                                   behavior_analysis: Dict[str, Any]) -> InterfaceConfig:
        """应用适应规则"""
        adapted_config = replace(current_config)
        
        # 按优先级排序规则
        sorted_rules = sorted(self.adaptation_rules, key=lambda r: r.priority, reverse=True)
        
        for rule in sorted_rules:
            if not rule.enabled:
                continue
            
            # 检查规则条件
            if await self._check_rule_conditions(rule, user_preferences, context, behavior_analysis):
                # 应用规则动作
                adapted_config = await self._apply_rule_actions(
                    rule, adapted_config, user_preferences, context
                )
                
                # 更新规则统计
                rule.usage_count += 1
        
        return adapted_config
    
    async def _check_rule_conditions(self, 
                                   rule: AdaptationRule,
                                   user_preferences: Optional[UserPreferences],
                                   context: Optional[Context],
                                   behavior_analysis: Dict[str, Any]) -> bool:
        """检查规则条件"""
        try:
            for condition in rule.conditions:
                condition_type = condition.get('type')
                operator = condition.get('operator')
                value = condition.get('value')
                
                if condition_type == 'component_usage':
                    component_usage = behavior_analysis.get('component_usage', {})
                    avg_usage = sum(component_usage.values()) / len(component_usage) if component_usage else 0
                    
                    if not self._compare_values(avg_usage, operator, value):
                        return False
                
                elif condition_type == 'expertise_level' and user_preferences:
                    if not self._compare_values(user_preferences.expertise_level, operator, value):
                        return False
                
                elif condition_type == 'screen_width' and context:
                    # 假设从上下文中获取屏幕宽度
                    screen_width = context.available_resources.get('screen_width', 1920)
                    if not self._compare_values(screen_width, operator, value):
                        return False
                
                elif condition_type == 'current_task' and context:
                    if not self._compare_values(context.current_task, operator, value):
                        return False
                
                elif condition_type == 'response_time':
                    # 假设从行为分析中获取响应时间
                    avg_response_time = behavior_analysis.get('avg_response_time', 1.0)
                    if not self._compare_values(avg_response_time, operator, value):
                        return False
            
            return True
            
        except Exception as e:
            print(f"规则条件检查失败: {e}")
            return False
    
    def _compare_values(self, actual: Any, operator: str, expected: Any) -> bool:
        """比较值"""
        try:
            if operator == '==':
                return actual == expected
            elif operator == '!=':
                return actual != expected
            elif operator == '<':
                return float(actual) < float(expected)
            elif operator == '<=':
                return float(actual) <= float(expected)
            elif operator == '>':
                return float(actual) > float(expected)
            elif operator == '>=':
                return float(actual) >= float(expected)
            elif operator == 'in':
                return actual in expected
            elif operator == 'not_in':
                return actual not in expected
            else:
                return False
        except (ValueError, TypeError):
            return False
    
    async def _apply_rule_actions(self, 
                                rule: AdaptationRule,
                                config: InterfaceConfig,
                                user_preferences: Optional[UserPreferences],
                                context: Optional[Context]) -> InterfaceConfig:
        """应用规则动作"""
        updated_config = replace(config)
        
        try:
            for action in rule.actions:
                action_type = action.get('type')
                target = action.get('target')
                value = action.get('value')
                
                if action_type == 'set_visibility':
                    # 设置组件可见性
                    if 'widget_visibility' not in updated_config.widget_visibility:
                        updated_config.widget_visibility = {}
                    
                    # 这里需要根据具体的组件来设置
                    # 简化实现：设置所有低使用率组件不可见
                    for comp_id in self.interface_components:
                        if self.interface_components[comp_id].priority < 5:
                            updated_config.widget_visibility[comp_id] = value
                
                elif action_type == 'switch_layout':
                    if value in self.layout_configurations:
                        layout = self.layout_configurations[value]
                        updated_config.layout_preferences = {
                            'layout_type': layout.layout_type.value,
                            'density': layout.theme_settings.get('density', 'medium')
                        }
                
                elif action_type == 'hide_advanced_components':
                    # 隐藏高级组件
                    advanced_components = [
                        comp_id for comp_id, comp in self.interface_components.items()
                        if 'advanced' in comp.title.lower() or comp.priority > 8
                    ]
                    
                    for comp_id in advanced_components:
                        updated_config.widget_visibility[comp_id] = False
                
                elif action_type == 'show_component':
                    if value in self.interface_components:
                        updated_config.widget_visibility[value] = True
                
                elif action_type == 'expand_main_content':
                    # 扩展主内容区域
                    updated_config.layout_preferences['main_content_expanded'] = True
                
                elif action_type == 'reduce_animations':
                    # 减少动画效果
                    updated_config.layout_preferences['animations_enabled'] = False
                
                elif action_type == 'lazy_load_components':
                    # 启用组件懒加载
                    updated_config.layout_preferences['lazy_loading'] = True
        
        except Exception as e:
            print(f"应用规则动作失败: {e}")
        
        return updated_config
    
    async def _optimize_layout(self, 
                             user_id: str,
                             config: InterfaceConfig,
                             user_preferences: Optional[UserPreferences],
                             behavior_analysis: Dict[str, Any]) -> InterfaceConfig:
        """优化布局"""
        optimized_config = replace(config)
        
        try:
            # 基于使用频率优化组件位置
            component_usage = behavior_analysis.get('component_usage', {})
            
            if component_usage:
                # 将高频使用的组件放在更显眼的位置
                high_usage_components = [
                    comp_id for comp_id, usage in component_usage.items()
                    if usage > 0.2  # 使用率超过20%
                ]
                
                # 更新组件可见性
                for comp_id in high_usage_components:
                    if comp_id in self.interface_components:
                        optimized_config.widget_visibility[comp_id] = True
            
            # 基于专业水平优化界面复杂度
            if user_preferences:
                if user_preferences.expertise_level == 'beginner':
                    # 简化界面
                    optimized_config.layout_preferences['complexity'] = 'simple'
                    optimized_config.font_size = max(14, optimized_config.font_size)
                    
                elif user_preferences.expertise_level == 'advanced':
                    # 提供更多功能
                    optimized_config.layout_preferences['complexity'] = 'advanced'
                    optimized_config.layout_preferences['show_advanced_tools'] = True
            
            # 基于交互效率优化
            interaction_efficiency = behavior_analysis.get('interaction_efficiency', 0.5)
            
            if interaction_efficiency < 0.7:
                # 效率较低，简化界面
                optimized_config.layout_preferences['simplified_navigation'] = True
                optimized_config.layout_preferences['show_tooltips'] = True
            
            # 基于布局密度偏好优化
            preferred_density = behavior_analysis.get('preferred_layout_density', 'medium')
            optimized_config.layout_preferences['density'] = preferred_density
            
            if preferred_density == 'high':
                optimized_config.font_size = min(12, optimized_config.font_size)
            elif preferred_density == 'low':
                optimized_config.font_size = max(16, optimized_config.font_size)
        
        except Exception as e:
            print(f"布局优化失败: {e}")
        
        return optimized_config
    
    def _record_adaptation(self, user_id: str, 
                          old_config: InterfaceConfig, 
                          new_config: InterfaceConfig):
        """记录适应历史"""
        try:
            adaptation_record = {
                'timestamp': datetime.now().isoformat(),
                'changes': self._calculate_config_changes(old_config, new_config),
                'trigger': 'automatic_adaptation'
            }
            
            self.adaptation_history[user_id].append(adaptation_record)
            
            # 限制历史记录长度
            if len(self.adaptation_history[user_id]) > 50:
                self.adaptation_history[user_id] = self.adaptation_history[user_id][-50:]
        
        except Exception as e:
            print(f"记录适应历史失败: {e}")
    
    def _calculate_config_changes(self, old_config: InterfaceConfig, 
                                new_config: InterfaceConfig) -> List[Dict[str, Any]]:
        """计算配置变化"""
        changes = []
        
        try:
            # 比较布局偏好
            if old_config.layout_preferences != new_config.layout_preferences:
                changes.append({
                    'type': 'layout_preferences',
                    'old_value': old_config.layout_preferences,
                    'new_value': new_config.layout_preferences
                })
            
            # 比较字体大小
            if old_config.font_size != new_config.font_size:
                changes.append({
                    'type': 'font_size',
                    'old_value': old_config.font_size,
                    'new_value': new_config.font_size
                })
            
            # 比较组件可见性
            if old_config.widget_visibility != new_config.widget_visibility:
                changes.append({
                    'type': 'widget_visibility',
                    'old_value': old_config.widget_visibility,
                    'new_value': new_config.widget_visibility
                })
            
            # 比较快捷键
            if old_config.shortcuts != new_config.shortcuts:
                changes.append({
                    'type': 'shortcuts',
                    'old_value': old_config.shortcuts,
                    'new_value': new_config.shortcuts
                })
        
        except Exception as e:
            print(f"计算配置变化失败: {e}")
        
        return changes
    
    async def record_user_experience_metrics(self, user_id: str, metrics: UserExperienceMetrics) -> bool:
        """记录用户体验指标"""
        try:
            metrics.user_id = user_id
            self.ux_metrics[user_id].append(metrics)
            
            # 更新组件使用统计
            for component, usage_time in metrics.interface_usage_pattern.items():
                if component not in self.component_usage_stats[user_id]:
                    self.component_usage_stats[user_id][component] = 0.0
                
                self.component_usage_stats[user_id][component] += usage_time
            
            # 限制指标历史长度
            if len(self.ux_metrics[user_id]) > 100:
                self.ux_metrics[user_id] = self.ux_metrics[user_id][-100:]
            
            return True
            
        except Exception as e:
            print(f"记录用户体验指标失败: {e}")
            return False
    
    async def get_interface_analytics(self, user_id: str, days: int = 30) -> Dict[str, Any]:
        """获取界面分析报告"""
        try:
            cutoff_date = datetime.now() - timedelta(days=days)
            
            # 获取指定时间范围内的UX指标
            recent_metrics = [
                metric for metric in self.ux_metrics.get(user_id, [])
                if metric.timestamp > cutoff_date
            ]
            
            if not recent_metrics:
                return {'error': '没有足够的用户体验数据'}
            
            analytics = {
                'user_id': user_id,
                'analysis_period_days': days,
                'total_sessions': len(recent_metrics),
                'interface_performance': {},
                'usage_patterns': {},
                'adaptation_effectiveness': {},
                'recommendations': []
            }
            
            # 计算界面性能指标
            avg_completion_time = sum(m.task_completion_time for m in recent_metrics) / len(recent_metrics)
            avg_click_efficiency = sum(m.click_efficiency for m in recent_metrics) / len(recent_metrics)
            avg_error_rate = sum(m.error_rate for m in recent_metrics) / len(recent_metrics)
            avg_satisfaction = sum(m.satisfaction_score for m in recent_metrics) / len(recent_metrics)
            
            analytics['interface_performance'] = {
                'average_task_completion_time': avg_completion_time,
                'average_click_efficiency': avg_click_efficiency,
                'average_error_rate': avg_error_rate,
                'average_satisfaction_score': avg_satisfaction
            }
            
            # 分析使用模式
            all_usage_patterns = defaultdict(float)
            for metric in recent_metrics:
                for component, usage_time in metric.interface_usage_pattern.items():
                    all_usage_patterns[component] += usage_time
            
            total_usage_time = sum(all_usage_patterns.values())
            if total_usage_time > 0:
                usage_percentages = {
                    comp: (time / total_usage_time) * 100
                    for comp, time in all_usage_patterns.items()
                }
                
                analytics['usage_patterns'] = {
                    'most_used_components': sorted(usage_percentages.items(), 
                                                 key=lambda x: x[1], reverse=True)[:5],
                    'total_interface_time': total_usage_time,
                    'component_usage_distribution': usage_percentages
                }
            
            # 分析适应效果
            adaptation_history = self.adaptation_history.get(user_id, [])
            recent_adaptations = [
                adapt for adapt in adaptation_history
                if datetime.fromisoformat(adapt['timestamp']) > cutoff_date
            ]
            
            analytics['adaptation_effectiveness'] = {
                'total_adaptations': len(recent_adaptations),
                'adaptation_types': Counter(
                    change['type'] for adapt in recent_adaptations
                    for change in adapt.get('changes', [])
                ),
                'performance_trend': self._calculate_performance_trend(recent_metrics)
            }
            
            # 生成改进建议
            analytics['recommendations'] = await self._generate_interface_recommendations(
                user_id, analytics
            )
            
            return analytics
            
        except Exception as e:
            print(f"获取界面分析失败: {e}")
            return {'error': '界面分析失败'}
    
    def _calculate_performance_trend(self, metrics: List[UserExperienceMetrics]) -> str:
        """计算性能趋势"""
        if len(metrics) < 5:
            return 'insufficient_data'
        
        # 将指标分为前半部分和后半部分
        mid_point = len(metrics) // 2
        early_metrics = metrics[:mid_point]
        recent_metrics = metrics[mid_point:]
        
        early_avg_satisfaction = sum(m.satisfaction_score for m in early_metrics) / len(early_metrics)
        recent_avg_satisfaction = sum(m.satisfaction_score for m in recent_metrics) / len(recent_metrics)
        
        if recent_avg_satisfaction > early_avg_satisfaction + 0.1:
            return 'improving'
        elif recent_avg_satisfaction < early_avg_satisfaction - 0.1:
            return 'declining'
        else:
            return 'stable'
    
    async def _generate_interface_recommendations(self, user_id: str, 
                                                analytics: Dict[str, Any]) -> List[str]:
        """生成界面改进建议"""
        recommendations = []
        
        try:
            performance = analytics.get('interface_performance', {})
            
            # 基于任务完成时间的建议
            avg_completion_time = performance.get('average_task_completion_time', 0)
            if avg_completion_time > 300:  # 超过5分钟
                recommendations.append("考虑简化界面布局以提高任务完成效率")
            
            # 基于点击效率的建议
            click_efficiency = performance.get('average_click_efficiency', 0)
            if click_efficiency < 0.7:
                recommendations.append("优化导航结构，减少不必要的点击操作")
            
            # 基于错误率的建议
            error_rate = performance.get('average_error_rate', 0)
            if error_rate > 0.1:
                recommendations.append("增加操作确认和帮助提示以减少错误")
            
            # 基于满意度的建议
            satisfaction = performance.get('average_satisfaction_score', 0)
            if satisfaction < 3.5:
                recommendations.append("考虑重新设计界面以提升用户体验")
            
            # 基于使用模式的建议
            usage_patterns = analytics.get('usage_patterns', {})
            most_used = usage_patterns.get('most_used_components', [])
            
            if most_used:
                top_component = most_used[0][0]
                recommendations.append(f"将'{top_component}'组件放置在更显眼的位置")
            
            # 基于适应效果的建议
            adaptation_effectiveness = analytics.get('adaptation_effectiveness', {})
            trend = adaptation_effectiveness.get('performance_trend', 'stable')
            
            if trend == 'declining':
                recommendations.append("当前界面适应可能不够理想，建议手动调整设置")
            elif trend == 'improving':
                recommendations.append("界面适应效果良好，继续保持当前设置")
        
        except Exception as e:
            print(f"生成界面建议失败: {e}")
        
        return recommendations[:5]  # 限制建议数量
    
    async def create_custom_layout(self, user_id: str, layout_name: str, 
                                 components: List[str]) -> LayoutConfiguration:
        """创建自定义布局"""
        try:
            # 验证组件存在性
            valid_components = []
            for comp_id in components:
                if comp_id in self.interface_components:
                    valid_components.append(self.interface_components[comp_id])
            
            if not valid_components:
                raise ValueError("没有有效的组件")
            
            # 创建自定义布局
            custom_layout = LayoutConfiguration(
                layout_id=f"custom_{user_id}_{len(self.layout_configurations)}",
                layout_type=LayoutType.CUSTOM,
                name=layout_name,
                description=f"用户{user_id}的自定义布局",
                components=valid_components,
                theme_settings={
                    "color_scheme": "custom",
                    "font_size": 14,
                    "density": "medium"
                }
            )
            
            self.layout_configurations[custom_layout.layout_id] = custom_layout
            
            return custom_layout
            
        except Exception as e:
            print(f"创建自定义布局失败: {e}")
            raise
    
    async def export_interface_data(self, user_id: str) -> Dict[str, Any]:
        """导出界面数据"""
        try:
            export_data = {
                'user_id': user_id,
                'export_date': datetime.now().isoformat(),
                'interface_config': None,
                'adaptation_history': [],
                'ux_metrics': [],
                'component_usage_stats': {}
            }
            
            # 导出界面配置
            if user_id in self.user_interface_configs:
                export_data['interface_config'] = asdict(self.user_interface_configs[user_id])
            
            # 导出适应历史
            if user_id in self.adaptation_history:
                export_data['adaptation_history'] = self.adaptation_history[user_id]
            
            # 导出UX指标
            if user_id in self.ux_metrics:
                export_data['ux_metrics'] = [
                    asdict(metric) for metric in self.ux_metrics[user_id]
                ]
            
            # 导出组件使用统计
            if user_id in self.component_usage_stats:
                export_data['component_usage_stats'] = self.component_usage_stats[user_id]
            
            return export_data
            
        except Exception as e:
            print(f"导出界面数据失败: {e}")
            return {'error': '界面数据导出失败'}
    
    async def delete_interface_data(self, user_id: str) -> bool:
        """删除界面数据"""
        try:
            if user_id in self.user_interface_configs:
                del self.user_interface_configs[user_id]
            
            if user_id in self.adaptation_history:
                del self.adaptation_history[user_id]
            
            if user_id in self.ux_metrics:
                del self.ux_metrics[user_id]
            
            if user_id in self.component_usage_stats:
                del self.component_usage_stats[user_id]
            
            return True
            
        except Exception as e:
            print(f"删除界面数据失败: {e}")
            return False